package com.geekcoding.geekoj.config;

import com.geekcoding.geekoj.nums.WebContextKey;
import lombok.NonNull;
import lombok.extern.log4j.Log4j2;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Log4j2
public class WebContextHolder {

    private static final ThreadLocal<Map<WebContextKey, Object>> CONTEXT = new InheritableThreadLocal<>();

    static {
        log.info("init WebContextHolder context ");
        CONTEXT.set(new HashMap<>());
    }

    public static Map<WebContextKey, Object> getOrBuild(){
        Map<WebContextKey, Object> map = CONTEXT.get();
        if(Objects.isNull(map)){
            map = new HashMap<>();
            CONTEXT.set(map);
        }
        return map;
    }


    public static void set(@NonNull WebContextKey key, Object value){
        getOrBuild().put(key, value);
    }

    public static <T> T get(@NonNull WebContextKey key){
        return (T) getOrBuild().get(key);
    }

    public static void remove(){
        CONTEXT.remove();
    }
}
